package com.shu.logsearch.es.service.impl;

import cn.hutool.core.io.FileUtil;
import com.shu.logsearch.es.model.Doc;
import com.shu.logsearch.es.service.TikaService;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Tree Cai
 * @date 2019/7/1
 */
@Component
public class TikaServiceImpl implements TikaService {
    @Override
    public Doc parserFileToDoc(File file) {
        Doc doc = new Doc();
        if (file == null)
            return doc;
        Parser parser = new AutoDetectParser();//自动解析器接口
        BodyContentHandler handler = new BodyContentHandler();
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            parser.parse(fileInputStream, handler, new Metadata(), new ParseContext());
            doc.setContent(handler.toString());
            BasicFileAttributes attributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
            doc.setTitle(FileUtil.getName(file));
            doc.setCreateTime(new Date(attributes.creationTime().toMillis()));
            doc.setUpdateTime(new Date(attributes.lastModifiedTime().toMillis()));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return doc;
    }

    @Override
    public List<Doc> parserFilesToDoc(List<File> fileList) {
        List<Doc> docList = new ArrayList<>();
        fileList.stream().forEach(file -> {
            docList.add(parserFileToDoc(file));
        });
        return docList;
    }
}
